package els;

import demo.Demo;
import jdbc.H3Dao;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import util.H3ElsEntity;
import util.RelaEntity;
import util.RelaTable;
import util.SearchEnums;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @ClassName: ElsDemo
 * @Description: els生成
 * @author: YuanWei
 * @date: 2019/01/29 16:48
 * @version: V1.0
 */
public class ElsDemo {
    private final static int TABLENAME=0;
    private final static int SHOWNAME=1;
    private final static int DBNAME=2;
    private final static int ORDER=3;
    private final static int HIDDEN=4;
    private final static int SHOWTYPE=5;
    private final static int ISSEARCH=6;
    private final static int ENUMSVALUE=7;
    private final static int RELATABLENAME=8;
    private final static int RELATABLECOLUMN=9;
    private final static int RELATABLESHOWCOLUMN=10;
    private final static int RELATABLEOTHERSHOWCOLUMN=11;
    private final static int RELATION=12;
    private final static int RELATIONTYPE=13;
    public static void main(String[] args) {
        String tempFilePath="D:/aaaa/els.xlsx";//源文件路径
        String targetFilePath = "D:/aaaa";//目标文件夹

        int index = 0;
        createStarted(tempFilePath,targetFilePath,index);
//        int begin = 0;
//        int totleCount = 6;
//        for (int i = begin; i < totleCount ; i++) {
//            createStarted(tempFilePath,targetFilePath,i);
//        }
        H3Dao.closeCon();
    }
    public static void createStarted(String tempFilePath,String targetFilePath,int index) {
        String tableComment = "";
        String tableName = "";
        //exlce 文件操作对象
        Workbook hssfWorkbook = null;
        //创建文件输入流
        FileInputStream is = null;
        try {
            is = new FileInputStream(new File(tempFilePath));
        } catch (FileNotFoundException e) {
            System.out.println("输入流创建失败！");
            e.printStackTrace();
        }
        try {
            hssfWorkbook = new XSSFWorkbook(is);
        } catch (Exception ex) {
            try {
                is = new FileInputStream(new File(tempFilePath));
                hssfWorkbook = new HSSFWorkbook(is);
            } catch (IOException e) {
                System.err.println("excel对象创建失败！");
                e.printStackTrace();
            }
        }
        //虚拟机运行结束删除文件
//	    new File(tempFilePath).deleteOnExit();
        if (is != null) {
            try {
                //关闭文件输入流
                is.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        List<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
        // 循环工作表Sheet
        Sheet hssfSheet = hssfWorkbook.getSheetAt(index);
        int columnsize = 0;//列总数
        List<H3ElsEntity> columnList = new ArrayList<H3ElsEntity>();
        int nameListSize = 0;
        // 循环行Row
        //HSSFHeader head= hssfSheet.getHeader();
        //读取excel中的内容到list中
        String sheetName="";
        int order=100;
        int relaOrder=0;
        H3ElsEntity h= new H3ElsEntity();
        List<RelaEntity> l = new ArrayList<RelaEntity>();
        for (int rowNum = 0; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
            Row hssfRow = hssfSheet.getRow(rowNum);
            if (hssfRow == null) {
                relaOrder=100-rowNum+1;
                break;
            }
        }
        for (int rowNum = 0; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
            Row hssfRow = hssfSheet.getRow(rowNum);
            sheetName = hssfSheet.getSheetName();
            if (hssfRow == null) {
                System.out.println(rowNum + "为空");
                break;
            }
            columnsize = hssfRow.getPhysicalNumberOfCells();
            if (rowNum == 0) {
//                tableComment = getValue(hssfRow.getCell(0)).trim();
//                tableName = getValue(hssfRow.getCell(1)).trim();
                continue;
            }
            H3ElsEntity column = new H3ElsEntity();
//            if (rowNum == 1) {
//                column.setPromoKey("true");
//            }
            if (getValue(hssfRow.getCell(TABLENAME)).length() == 0) {
                continue;
            }
            tableName = getValue(hssfRow.getCell(TABLENAME));
            if (tableName == null || tableName.length() < 1) {
                System.out.println("表名错误");
                return;
            }

            String tableId = H3Dao.queryTableIdByName(tableName);
            if (tableId == null) {
                return;
            }
            column.setTableId(tableId);
            column.setTableName(getValue(hssfRow.getCell(TABLENAME)));
            column.setColumnTitle(getValue(hssfRow.getCell(SHOWNAME)));
            String columnName = getValue(hssfRow.getCell(DBNAME));
            column.setColumnKey(columnName);
            String columnId = H3Dao.queryColumnIdByName(tableId, columnName);
            if(!checkIsNull(columnName,columnId))return;
            column.setColumnId(columnId);

//            column.setOrder(getValue(hssfRow.getCell(ORDER)));
            column.setOrder(order--+"");
            String hidden = getValue(hssfRow.getCell(HIDDEN));
            if (hidden != null && !"0".equals(hidden)&&hidden.length()>0){
                column.setColumnHidden(hidden);
            }
            String showType = getValue(hssfRow.getCell(SHOWTYPE));
            column.setEntityColumnType(showType);//展示类型
            column.setColumnTypeDisabled(getValue(hssfRow.getCell(ISSEARCH)));
            String enumsValue = getValue(hssfRow.getCell(ENUMSVALUE));
            if(enumsValue!=null&&enumsValue.length()>0) {//解析枚举
                List<SearchEnums> searchEnumsList = new ArrayList<SearchEnums>();
                String[] strs = enumsValue.split(",");
                for (int i = 0; i < strs.length ; i++) {
                    String[] enumsStrs = strs[i].split(":");
                    SearchEnums searchEnums = new SearchEnums();
                    searchEnums.setTypeSetValue(enumsStrs[0]);
                    searchEnums.setTypeSetLabel(enumsStrs[1]);
                    searchEnumsList.add(searchEnums);
                }
                column.setSearchEnumsList(searchEnumsList);

            }
            h.setTableName(tableName);
            String relationTableName = getValue(hssfRow.getCell(RELATABLENAME));//关联表名
            String relationTableColumnName=getValue(hssfRow.getCell(RELATABLECOLUMN));//关联字段名
            String relationTableShowColumnName = getValue(hssfRow.getCell(RELATABLESHOWCOLUMN));//关联展示字段名
            String relation = getValue(hssfRow.getCell(RELATION));//关联关系
            String relationtype =getValue(hssfRow.getCell(RELATIONTYPE));//关联类型
            if(relationTableName.length()>0) {
                String relationTableId = H3Dao.queryTableIdByName(relationTableName);
                if (!checkIsNull(relationTableName, relationTableId)) return;
                if(relation.length()>0){
                    String[] strs = relation.split(",");
                    StringBuffer tempColumnName=new StringBuffer();
                    StringBuffer tempColumnIdStr = new StringBuffer();
                    for (int i=0;i<strs.length;i++){
                        String tempColumn = strs[i];
                        String tempColumnId = H3Dao.queryColumnIdByName(relationTableId,tempColumn);
                        tempColumnName.append("\"").append(tempColumn).append("\",");
                        tempColumnIdStr.append("\"").append(tempColumnId).append("\",");
                    }
                    tempColumnName.setLength(tempColumnName.length()-1);
                    tempColumnIdStr.setLength(tempColumnIdStr.length()-1);
                    RelaEntity r = new RelaEntity();
                    r.setTableId(relationTableId);
                    r.setTableName(relationTableName);
                    r.setColumnIds(tempColumnIdStr.toString());
                    r.setColumnNames(tempColumnName.toString());
                    r.setRelationType(relationtype);
                    l.add(r);
                    h.setRelaEntityList(l);
                    h.setTableNames(tempColumnName.toString());
                    h.setTableIds(tempColumnIdStr.toString());
                }
                String relationTableColumnId = H3Dao.queryColumnIdByName(relationTableId,relationTableColumnName);
                if(!checkIsNull(relationTableColumnName,relationTableColumnId)) return;
                String relationTableShowColumnId = H3Dao.queryColumnIdByName(relationTableId,relationTableShowColumnName);
                if(!checkIsNull(relationTableShowColumnName,relationTableShowColumnId))return;
                column.setRelationTableName(relationTableName);//关联表表名
                column.setRelationTableId(relationTableId);//关联表表ID
                column.setRelationColumnName(relationTableColumnName);//关联表表字段名
                column.setRelationColumnId(relationTableColumnId);//关联表表字段ID
                column.setRelationShowColumnId(relationTableShowColumnId);//关联表展示字段ID
                column.setRelationShowColumnName(relationTableShowColumnName);//关联表展示字段名

                String relationTableOtherShowColumnName = getValue(hssfRow.getCell(RELATABLEOTHERSHOWCOLUMN));
                if(relationTableOtherShowColumnName!=null&&relationTableOtherShowColumnName.length()>0){
                    List<RelaTable> relaList = new ArrayList<RelaTable>();//解析关联表字段
                    String[] temps = relationTableOtherShowColumnName.split(",");
                    for (int i = 0; i < temps.length; i++) {
                        String[] temp = temps[i].split(":");
                        RelaTable r = new RelaTable();
                        r.setColumnTypeName("input");
                        r.setColumnTypeDisabled("0");
                        r.setColumnTypePlaceholder(temp[1]);
                        //TODO 设置顺序
//                        r.setOrder(relaOrder--+"");//关联表最后顺序
                        r.setOrder(order--+"");//正常顺序
                        String typeColumnId = H3Dao.queryColumnIdByName(relationTableId,temp[0]);
                        if(!checkIsNull(temp[0],typeColumnId))return;
                        r.setColumnId(typeColumnId);
                        r.setColumnKey(temp[0]);
                        relaList.add(r);
                    }
                    column.setRelaTableList(relaList);
                }
            }
            columnList.add(column);
        }
//        targetFilePath+="/els/"+sheetName+".txt";

        Demo.StringToFile(targetFilePath+"/els/"+sheetName+".txt", ElsBuildStr.budildStr(columnList));
//        Demo.StringToFile(targetFilePath+"/els/"+sheetName+"_数据采集.txt",ElsBuildStr.buildS(h));
//        System.out.println(ElsBuildStr.buildS(h));
        System.out.println(sheetName+"-----完成 --"+columnList.get(0).getTableId());

    }
    private static String getValue(Cell hssfCell) {
		/*if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {
			// 返回布尔类型的值
			return String.valueOf(hssfCell.getBooleanCellValue());
		} else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {
			// 返回数值类型的值
			return String.valueOf(hssfCell.getNumericCellValue());
		} else {  */
        // 返回字符串类型的值
        if(hssfCell==null)return "";

        hssfCell.setCellType(Cell.CELL_TYPE_STRING);
        return hssfCell.getStringCellValue().toString().trim();
        /*}  */
    }
    private static boolean checkIsNull(String name,String value){
        if(value==null||value.length()<1){
            System.out.println(name+"未查到数据");
//            return false;
        }
        return true;
    }
}
